<%@ page contentType="image/png" pageEncoding="utf-8"%>
<%@ page import="java.io.*" %>
<%@ page import="java.util.Random" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.Collection" %>
<%@ page import="java.util.Collections" %>
<%@ page import="javax.cache.Cache" %>
<%@ page import="javax.cache.CacheManager" %>
<%@ page import="com.google.appengine.api.images.*" %>
<%
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
 
    ImagesService imagesService = ImagesServiceFactory.getImagesService();
    try {
        byte[] imgData;
        String imgName = "WEB-INF/captcha.png";
        Cache cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        if (cache.containsKey(imgName)) {
            imgData = (byte[]) cache.get(imgName);
        } else {
            FileInputStream fileInputStream = new FileInputStream(imgName);
            imgData = new byte[fileInputStream.available()];
            fileInputStream.read(imgData);
            fileInputStream.close();
            cache.put(imgName, imgData);
        }
        Image bigImg = ImagesServiceFactory.makeImage(imgData);
 
        Random random = new Random();
        Collection<Composite> compositeArray = new ArrayList();
        int row = random.nextInt(10);
        String captcha = "";
 
        for (int i = 0; i < 4; i++) {
            int column = random.nextInt(10);
            captcha += String.valueOf(column);
            Transform crop = ImagesServiceFactory.makeCrop(0.1f*column, 0.1f*row, 0.1f*(column+1), 0.1f*(row+1));
            Image unitImg = ImagesServiceFactory.makeImage(imagesService.applyTransform(crop, bigImg).getImageData());
            bigImg.setImageData(imgData);
            Composite composite = ImagesServiceFactory.makeComposite(unitImg, i * 12 + 1, 0, 1.0f, Composite.Anchor.TOP_LEFT);
            compositeArray.add(composite);
        }
        System.out.println(captcha);
        request.getSession(true).setAttribute("captcha", captcha);
        System.out.println(request.getSession(true).getAttribute("captcha"));
 		
        Image finalImg = imagesService.composite(compositeArray, 50, 20, 0);
        OutputStream output = response.getOutputStream();
        output.write(finalImg.getImageData());
        output.flush();
        out.clear();
        out = pageContext.pushBody();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
%>